<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>canvas实现天上掉小球</title>

    <style>
        html,body{
            margin: 0;
            width:100%;
            height:100%;
        }
    </style>
</head>

<body>
    <canvas id="canvas" style="border:1px solid #ccc;background-color:black;">
        当前浏览器不支持canvas,请选择其他浏览器
    </canvas>

    <script>
        var ctx;
        var canvas;
        var balls = [];
        var colors = ['#EE2C2C','#A52A2A','#9ACD32','#7171C6','#436EEE','#FF6EB4','#CDAD00','#CDCDC1','#6E8B3D','#9F79EE'];

        window.onload = function(){
            canvas = document.getElementById("canvas");
            ctx = canvas.getContext("2d");

            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            start();
        }

        function start() {
            createBalls();
            setInterval(function () {
                ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
                for(var i=0;i<balls.length;i++){
                    ctx.fillStyle = balls[i].color;

                    ctx.beginPath();                                
                    ctx.arc(balls[i].startx, balls[i].starty, balls[i].radius, 0, Math.PI * 2); 
                    ctx.closePath();
                    ctx.fill();

                    balls[i].vy += balls[i].g
                    balls[i].startx = balls[i].startx + balls[i].vx;
                    balls[i].starty = balls[i].starty + balls[i].vy;

                    if (balls[i].starty + balls[i].radius*2 >= window.innerHeight) {
                        balls[i].starty = window.innerHeight-balls[i].radius*2;
                        balls[i].vy = balls[i].vy * (-0.8)
                    }                          
                }
                updateBalls();
            }, 20);
        }

        function createBalls() {
            //创建40个小球
            for(var i = 0; i<40;i++){
                balls[balls.length] = creatBall();
            }
        
        }

        function creatBall(){
            var ball = {
                startx:1000*(Math.random()),
                starty:20*(Math.random()+1),
                radius:10*(Math.random()+1),
                vx:2*Math.random()+1,
                vy:0,
                g:0.2*Math.random()+1,
                color:colors[Math.floor(Math.random()*10)]
            }

            return ball;
        }

        function updateBalls(){
            for(var i = 0; i<balls.length; i++){
                //控制小球数量40个
                if(balls[i].startx + balls[i].radius*2 >= window.innerWidth ){
                    balls[i] = creatBall();
                }
            }
        }

        
    </script>
</body>

</html>